package cn.demoncat.util.lang.entity;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

/**
 * 参照列表排序器
 *
 * @author 延晓磊
 * @since 2023年01月15日
 */
public class ReferComparator<T, R> implements Comparator<T> {

    // 参照列表
    private List<R> referList;
    // 获取参照元素的方法
    private Function<T,R> referGetter;

    /**
     * 构建
     *
     * @param referList
     * @param referGetter
     * @return
     */
    public static <T,R> ReferComparator<T,R> build(List<R> referList, Function<T,R> referGetter){
        ReferComparator<T, R> comparator = new ReferComparator<>();
        comparator.referList = referList;
        comparator.referGetter = referGetter;
        return comparator;
    }

    @Override
    public int compare(T o1, T o2) {
        return Integer.compare(referList.indexOf(referGetter.apply(o1)), referList.indexOf(referGetter.apply(o2)));
    }

}
